import 'dart:io';

import 'package:extended_image/extended_image.dart';
import 'package:flutter/material.dart';
import 'package:xws/helpers/safe_value_notifier.dart';
import 'package:xws/utils/app_util.dart';
import 'package:xws/utils/log_util.dart';
import 'package:xws/utils/storage_util.dart';
import 'package:xws/utils/theme_util.dart';
import 'package:xws/widgets/app_btn.dart';
import 'package:xws/widgets/ex_value_builder.dart';

///清理按钮
class ClearItem extends StatefulWidget {
  const ClearItem({Key? key}) : super(key: key);
  @override
  _ClearItemState createState() => _ClearItemState();
}

class _ClearItemState extends State<ClearItem> {
  ///缓存大小
  final SafeValueNotifier<String> _cacheSize = SafeValueNotifier<String>('0.0 MB  ');

  @override
  void initState() {
    super.initState();
    _ready();
  }

  @override
  void dispose() {
    _cacheSize.dispose();
    super.dispose();
  }

  ///目录大小
  int _dirStatSync(String dirPath) {
    int totalSize = 0;
    final Directory dir = Directory(dirPath);
    try {
      if (dir.existsSync()) {
        dir.listSync(recursive: true, followLinks: false).forEach((FileSystemEntity entity) {
          if (entity is File) {
            totalSize += entity.lengthSync();
          }
        });
      }
    } catch (e) {
      debug(e.toString());
    }

    return totalSize;
  }

  ///计算缓存大小
  Future<void> _ready() async {
    ///图片缓存
    final int imgCacheSize = await getCachedSizeBytes();

    ///压缩缓存
    final int fileCacheSize = _dirStatSync(await getLocalPath('temp'));

    _cacheSize.value = ((imgCacheSize + fileCacheSize) / 1048576).toStringAsFixed(2) + ' MB  ';

    debug('缓存大小:${_cacheSize.value}');
  }

  ///清理缓存
  Future<void> _clearCache() async {
    try {
      final bool? r = await tips<bool>('确认清除缓存?');

      if (r == null || !r) return;

      ///清理图片缓存
      clearDiskCachedImages();

      ///清理压缩缓存
      Directory(await getLocalPath('temp')).delete(recursive: true);

      debug('清理完成');

      await _ready();
    } catch (e) {
      error('清理缓存出错:$e');
    }
  }

  @override
  Widget build(BuildContext context) {
    return AppBtn(
      onTap: _clearCache,
      child: Row(
        children: <Widget>[
          Text(
            '清理缓存',
            style: TextStyle(
              fontSize: 15,
              fontWeight: FontWeight.bold,
              color: black(context).withOpacity(0.7),
            ),
          ),
          const Spacer(),
          _buildValueWidget,
          const Icon(Icons.arrow_forward_ios_rounded, size: 16),
        ],
      ),
      padding: const EdgeInsets.symmetric(horizontal: 20),
      alignment: Alignment.center,
      color: white(context),
      height: 56,
      radius: 0,
    );
  }

  ///构建缓存大小
  Widget get _buildValueWidget {
    return ExValueBuilder<String>(
      valueListenable: _cacheSize,
      builder: (_, String s, __) {
        return Text(
          s,
          style: TextStyle(
            color: disable(context),
            fontSize: 12,
            fontWeight: FontWeight.bold,
          ),
        );
      },
    );
  }
}
